package com.dage.salesflow.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import com.dage.salesflow.constant.SysConstant;
import com.dage.salesflow.excel.model.UserExcel;
import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.model.User;
import com.dage.salesflow.service.UserService;
import com.jfinal.aop.Inject;
import com.jfinal.core.paragetter.Para;
import io.jboot.web.controller.annotation.RequestMapping;

import java.io.File;
import java.io.IOException;

@RequestMapping("/user")
public class UserController extends BaseController {
	@Inject
	UserService userService;

	public void listByPage(@Para("") User model, int page, int limit) {
		renderPageJson(userService.listByPage(model, page, limit));
	}

	public void add(@Para("") User user) throws Exception {
		renderJson(userService.add(user));
	}

	public void edit(@Para("") User user) throws Exception {
		if (user.getStatus() == User.STATUS_LOCK) {
			//封停账号同时踢下线
			StpUtil.logoutByLoginId(user.getId());
		}
		renderJson(userService.edit(user));
	}

	public void reset(int id, String password) {
		//		StpUtil.checkPermission("user:update");
		User user = new User();
		user.setId(id);
		user.setPassword(SaSecureUtil.aesEncrypt(SysConstant.PASS_WORD_KEY, password));
		if (userService.update(user)) {
			renderJson(Ret.ok());
		} else {
			renderJson(Ret.err("重置失败"));
		}
	}

	public void resetPwd(String password, String old) {
		//		StpUtil.checkPermission("user:update");
		User loginUser = userService.getById(StpUtil.getLoginIdAsInt());
		if (loginUser.getPassword().equals(SaSecureUtil.aesEncrypt(SysConstant.PASS_WORD_KEY, old))) {
			User user = new User();
			user.setId(StpUtil.getLoginIdAsInt());
			user.setPassword(SaSecureUtil.aesEncrypt(SysConstant.PASS_WORD_KEY, password));
			if (userService.update(user)) {
				renderJson(Ret.ok());
			} else {
				renderJson(Ret.err("重置失败"));
			}
		} else {
			renderJson(Ret.err("密码错误"));
		}
	}

	public void kick(int id) {
		StpUtil.checkRole("role1");
		StpUtil.logoutByLoginId(id);
		renderJson(Ret.ok());
	}

	public void updateAreaByIds(int areaId, String ids) {
		renderJson(userService.updateAreaByIds(areaId, ids.split(",")));
	}

	public File importTemplate() throws IOException {
		return importTemplateFile(UserExcel.class);
	}

	public File export(@Para("") User model) throws Exception {
		return userService.export(model);
	}

	public void importData(File file, boolean update) {
		renderJson(userService.importData(file, update));
	}
}
